package com.luobo.shiro.controller;

import com.luobo.shiro.bean.CacheUser;
import com.luobo.shiro.bean.Result;
import com.luobo.shiro.config.MySessionManager;
import com.luobo.shiro.config.ShiroSessionListener;
import com.luobo.shiro.domain.entity.User;
import com.luobo.shiro.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.serializer.ObjectSerializer;
import org.crazycake.shiro.serializer.RedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description：登录Controller
 */
@Slf4j
@RestController
public class LoginController {

    @Resource
    private IUserService userService;
    @Autowired
    private MySessionManager mySessionManager;
    @Resource
    private ShiroSessionListener shiroSessionListener;
    @Autowired
    private RedisManager redisManager;

    @GetMapping("/getUser")
    public Result getUser() {
        Collection<Session> activeSessions = mySessionManager.getSessionDAO().getActiveSessions();
        return Result.success(activeSessions);
    }

    @GetMapping("/get")
    public Result get() throws Exception{
        RedisSerializer valueSerializer = new ObjectSerializer();
        Set<byte[]> keys = redisManager.keys("user:auth:*".getBytes("UTF-8"));
        HashSet set = new HashSet();
        if (keys != null && keys.size() > 0) {
            Iterator iterator = keys.iterator();
            while(iterator.hasNext()) {
                byte[] key = (byte[])iterator.next();
                Object deserialize = valueSerializer.deserialize(redisManager.get(key));
                set.add(deserialize);
            }
        }
        return Result.success(set);
    }




    /**
     *  登录
     * @return 登录结果
     */
    @GetMapping("/login")
    public Result login(@Valid User user) {
        log.debug("进入登录.....");
        String userName = user.getUserName();
        String password = user.getPassword();
        CacheUser loginUser = userService.login(userName, password);
        // 登录成功返回用户信息
        AtomicInteger sessionCount = shiroSessionListener.getSessionCount();
        Map<String,Object> map = new HashMap<>();
        map.put("user",loginUser);
        map.put("userCount",sessionCount);
        return Result.success(map);
    }

    /**
     * description: 退出
     */
    @RequestMapping("/logout")
    public Result logOut() {
        userService.logout();
        return Result.success("退出成功!");
    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     */
    @RequestMapping("/unAuth")
    public Result unAuth() {
        return Result.error("用户未登录!");
    }

    /**
     * 未授权，无权限，此处返回未授权状态信息由前端控制跳转页面
     */
    @RequestMapping("/unauthorized")
    public Result unauthorized() {
        return Result.error("用户无权限!");
    }
}
